﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using TERP.HTCServiceClient.Views;
using TERP.HTCServiceClient.Entities.Auth;
using TERP.HTCServiceClient.Common;
using TERP.HTCServiceClient.DbServices;

namespace TERP.HTCServiceClient.Views.Auth
{
	public partial class FrmMapGrpUser : FrmMdiBase
	{
		#region Declarations
		private const string CAPTION_INDEX = "STT";
		private const string CAPTION_GRP_CODE = "Mã nhóm";
		private const string CAPTION_GRP_NAME = "Tên nhóm";
		private const string CAPTION_EDIT_STATUS = "Trạng thái";
		//
		private const string CAPTION_USR_CODE = "Mã người dùng";
		private const string CAPTION_USR_NAME = "Tên người dùng";
		private const string CAPTION_DEALER_CODE = "Mã đại lý";
		private const string CAPTION_FLAG_ACTIVE = "Trạng thái active";
		private const string CAPTION_FLAG_SYS_ADMIN = "Sys Admin";
		//
		private const string FIELD_EDIT_STATUS = "Col_Edit_Status";
		//
		private GroupCollection _grpCollection;
		private DataTable _dtbAllUser;
		#endregion

		public FrmMapGrpUser()
		{
			InitializeComponent();
		}

		private void FrmMapGrpUser_Load(object sender, EventArgs e)
		{
			InitGrid();
			InitGridItemEditor();
			InitControl();
			SetLanguage();
			this.LoadGroup();
		}

		private void InitControl()
		{
		}

		/// <summary>
		/// 
		/// </summary>
		private void SetLanguage()
		{
			this.grpGroup.Text = "Nhóm";
			this.btnApply.Text = "Lưu";
			this.btnClose.Text = "Đóng";
			this.btnReload.Text = "Tải lại";
			//
			this.lblUserBelong.Text = "Người dùng đã gán";
			this.lblUserNotBelong.Text = "Người dùng chưa gán";
		}

		/// <summary>
		/// 
		/// </summary>
		private void InitGrid()
		{
			SetGridViewStyle(gviewGroup);
			SetGridViewStyle(gviewUserBelong);
			SetGridViewStyle(gviewUserNotBelong);
			gviewUserBelong.BorderStyle = BorderStyles.Default;
			gviewUserNotBelong.BorderStyle = BorderStyles.Default;
			//grid grp
			gridColIdx.Caption = CAPTION_INDEX;
			gridColGrpCode.Caption = CAPTION_GRP_CODE;
			gridColGrpName.Caption = CAPTION_GRP_NAME;
			gridColEditStatus.Caption = CAPTION_EDIT_STATUS;
			//
			gridColIdx.FieldName = TblCommon.Index;
			gridColGrpCode.FieldName = TblGroup.Group_Code;
			gridColGrpName.FieldName = TblGroup.Group_Name;
			gridColEditStatus.FieldName = FIELD_EDIT_STATUS;
			//grid user
			gridColBelongUc.Caption = CAPTION_USR_CODE;
			gridColBelongUn.Caption = CAPTION_USR_NAME;
			gridColNotBelongUc.Caption = CAPTION_USR_CODE;
			gridColNotBelongUn.Caption = CAPTION_USR_NAME;
			//
			gridColBelongUc.FieldName = TblUser.User_Code;
			gridColBelongUn.FieldName = TblUser.User_Name;
			gridColNotBelongUc.FieldName = TblUser.User_Code;
			gridColNotBelongUn.FieldName = TblUser.User_Name;
			//
			this.SetGridViewBestFitColumn(gviewUserBelong);
			this.SetGridViewBestFitColumn(gviewUserNotBelong);
			gviewUserBelong.DataSourceChanged += new EventHandler(gview_DataSourceChanged);
			gviewUserNotBelong.DataSourceChanged += new EventHandler(gview_DataSourceChanged);
		}

		/// <summary>
		/// 
		/// </summary>
		private void InitGridItemEditor()
		{
			reposImgCmbBox.SmallImages = EmbeddedRes.Instance.ImageListEditStatus;
			reposImgCmbBox.Items.Clear();
			reposImgCmbBox.Items.AddRange(new ImageComboBoxItem[] { 
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_NONE, EditStatus.IMG_IDX_STT_NONE), 
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_EDIT, EditStatus.IMG_IDX_STT_EDIT),
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_DELETE, EditStatus.IMG_IDX_STT_DELETE),
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_NEW, EditStatus.IMG_IDX_STT_NEW)
			});
		}

		/// <summary>
		/// 
		/// </summary>
		private void LoadGroup()
		{
			gridGroup.DataSource = null;
			gridUserBelong.DataSource = null;
			gridUserNotBelong.DataSource = null;
			//
			try
			{
				GroupService grpSv = new GroupService();
				_grpCollection = grpSv.GetGroup();
				UserService usrSv = new UserService();
				UserCollection usrCollection = usrSv.GetUser();
				_dtbAllUser = usrCollection.DataTableUser;
			}
			catch (Exception ex)
			{
				Util.ShowExceptionBox(ex);
				return;
			}
			DataTable dtblGrp = _grpCollection.DataTableGroup;
			dtblGrp.Columns.AddRange(new DataColumn[] {
				new DataColumn(TblCommon.Index,typeof(int)),
				new DataColumn(FIELD_EDIT_STATUS,typeof(string))
			});
			int count = 0;
			foreach (DataRow dtRow in dtblGrp.Rows)
			{
				count++;
				dtRow[TblCommon.Index] = count;
				dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_NONE;
			}
			//
			gridGroup.DataSource = dtblGrp;
            if (count > 0)
                gviewGroup.SelectRow(0);
		}

		private void gviewGroup_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
		{
			int rowHdl = e.FocusedRowHandle;
			gridUserBelong.DataSource = null;
			gridUserNotBelong.DataSource = null;
			if (_grpCollection == null)
				return;
			string grpCode = Convert.ToString(gviewGroup.GetRowCellValue(rowHdl, TblGroup.Group_Code));
			//
			DataTable dtblUserBelong = null;
			Group grp = _grpCollection.FindGroup(grpCode);
			if (grp == null)
				return;
			dtblUserBelong = grp.ListUserBelongTo.DataTableUser;
			//
			gridUserBelong.DataSource = dtblUserBelong;
			//
			List<string> lstUcBelong = new List<string>();
			foreach (DataRow dtRow in dtblUserBelong.Rows){
                if (dtRow.RowState == DataRowState.Deleted)
                    continue;
				lstUcBelong.Add((string)dtRow[TblUser.User_Code]);
			}
			//
			DataTable dtblUserNotBelong = _dtbAllUser.Copy();
			foreach (string userCode in lstUcBelong)
			{
				foreach (DataRow dtRow in dtblUserNotBelong.Rows)
				{
					string tmp = (string)dtRow[TblUser.User_Code];
					if (userCode.Equals(tmp))
					{
						dtblUserNotBelong.Rows.Remove(dtRow);
						break;
					}
				}
			}
			gridUserNotBelong.DataSource = dtblUserNotBelong;
		}

		private void btnReload_Click(object sender, EventArgs e)
		{
			this.LoadGroup();
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="gviewFrom"></param>
		/// <param name="gviewTo"></param>
		private void MoveSelectRow(GridView gviewFrom, GridView gviewTo)
		{
			foreach (int rowHandle in gviewFrom.GetSelectedRows())
			{
				string userCode = (string)gviewFrom.GetRowCellValue(rowHandle, TblUser.User_Code);
				string userName = (string)gviewFrom.GetRowCellValue(rowHandle, TblUser.User_Name);
				DataTable dtblTo = (DataTable)gviewTo.GridControl.DataSource;
				DataRow dtRow = dtblTo.NewRow();
				dtRow[TblUser.User_Code] = userCode;
				dtRow[TblUser.User_Name] = userName;
				//
				dtblTo.Rows.Add(dtRow);
			}
			//
			gviewFrom.DeleteSelectedRows();
			this.SetCurrentGroupEditState();
		}

		private void btnRemove_Click(object sender, EventArgs e)
		{
			this.MoveSelectRow(gviewUserBelong, gviewUserNotBelong);
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			this.MoveSelectRow(gviewUserNotBelong, gviewUserBelong);
		}

		private void btnAddAll_Click(object sender, EventArgs e)
		{
			gviewUserNotBelong.SelectAll();
			this.MoveSelectRow(gviewUserNotBelong, gviewUserBelong);
		}

		private void btnRemoveAll_Click(object sender, EventArgs e)
		{
			gviewUserBelong.SelectAll();
			this.MoveSelectRow(gviewUserBelong, gviewUserNotBelong);
		}

		private void SetCurrentGroupEditState()
		{
			DataRow dtRow = gviewGroup.GetFocusedDataRow();
			if (dtRow != null)
				dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_EDIT;
		}

		private void btnApply_Click(object sender, EventArgs e)
		{
			//
			List<string> lstGrpCode = new List<string>();
			DataTable dtbMapGrpUsr = new DataTable();
			dtbMapGrpUsr.Columns.AddRange(new DataColumn[]{
				new DataColumn(TblGroup.Group_Code),
				new DataColumn(TblUser.User_Code),
			});
			//
            for (int rowHandle = 0; rowHandle < gviewGroup.RowCount; rowHandle++)
            {
                string grpCode = (string)gviewGroup.GetRowCellValue(rowHandle, TblGroup.Group_Code);
                string editStatus = (string)gviewGroup.GetRowCellValue(rowHandle, FIELD_EDIT_STATUS);
                if (editStatus.Equals(EditStatus.ITEM_VALUE_STT_EDIT))
                {
                    lstGrpCode.Add(grpCode);
                    Group grp = _grpCollection.FindGroup(grpCode);
                    DataTable dtblUserBelong = grp.ListUserBelongTo.DataTableUser;
                    foreach (DataRow dtRow in dtblUserBelong.Rows)
                    {
                        if (dtRow.RowState == DataRowState.Deleted)
                            continue;
                        DataRow dtRowMap = dtbMapGrpUsr.NewRow();
                        dtRowMap[TblUser.User_Code] = dtRow[TblUser.User_Code];
                        dtRowMap[TblGroup.Group_Code] = grpCode;
                        dtbMapGrpUsr.Rows.Add(dtRowMap);
                    }
                }
            }
			//
			if (lstGrpCode.Count == 0)
				return;
			try
			{
				GroupService grpSv = new GroupService();
				DataSet dsMap = new DataSet();
				dsMap.Tables.Add(dtbMapGrpUsr);
				grpSv.MapUserToGroup(lstGrpCode,dsMap);
                this.LoadGroup();
			}
			catch (Exception ex)
			{
				Util.ShowExceptionBox(ex);
			}
		}

		private void splitContainerControl_Panel2_SizeChanged(object sender, EventArgs e)
		{
			int borderPadding = 6;
			int controlSpacing = 20;
			int btnWidth = 88;
			int usedWidth = borderPadding * 2 + controlSpacing * 2 + btnWidth;
			int widthParent = splitContainerControl.Panel2.Width;
			int widthGrid = (widthParent - usedWidth) / 2;
			//
			int xOffset = borderPadding;
			gridUserBelong.Left = xOffset;
			gridUserBelong.Width = widthGrid;
			//
			xOffset += widthGrid + controlSpacing;
			btnAdd.Left = xOffset;
			btnAddAll.Left = xOffset;
			btnRemove.Left = xOffset;
			btnRemoveAll.Left = xOffset;
			//
			xOffset += controlSpacing + btnWidth;
			lblUserNotBelong.Left = xOffset;
			gridUserNotBelong.Left = xOffset;
			gridUserNotBelong.Width = widthGrid;
			//button y
			int buttonSpacing = 6;
			int heightBtn = 26;
			int usedHeight = 4 * 26 + 3 * buttonSpacing;
			int heightGrid = gridUserBelong.Height;
			int yOffset = (heightGrid - usedHeight) / 2;
			if (yOffset < gridUserBelong.Top)
				yOffset = gridUserBelong.Top;
			btnAdd.Top = yOffset;
			yOffset += heightBtn + buttonSpacing;
			btnRemove.Top = yOffset;
			yOffset += heightBtn + buttonSpacing;
			btnAddAll.Top = yOffset;
			yOffset += heightBtn + buttonSpacing;
			btnRemoveAll.Top = yOffset;
		}
	}
}
